<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>2-7 通过鼠标控制绘制</title>
  <script src="../lib/index.js"></script>
  <style>
    * {
      margin: 0;
      padding: 0 !important;
    }
    body {
      border: 1px solid #ccc;
    }
    #canvas {
      margin: 50px auto 0;
      display: block;
      background: yellow;
    }
  </style>
</head>
<body>
  <canvas id="canvas" width="400" height="400">
    此浏览器不支持canvas
  </canvas>

  <script>
    const ctx = document.getElementById('canvas');
    const gl = ctx.getContext('webgl');

    /**
     * 创建着色器源码
     * */
    // 顶点着色器
    // gl_Position vec4(0.0, 0.0, 0.0, 1.0) x, y, z, w齐次坐标（x/w, y/w, z/w）
    const VERTEX_SHADER_SOURCE = `
      attribute vec4 aPosition;
      void main() {
        // 要绘制的点的坐标
        gl_Position = aPosition;    // vec4(0.0,0.0,0.0,1.0)
        // 点的大小
        gl_PointSize = 30.0;
      }
    `;

    // 片元着色器
    // gl_FragColor vec4(1.0, 0.0, 0.0, 1.0) r, b, g, a
    const FRAGMENT_SHADER_SOURCE = `
      void main() {
        gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
      }
    `;

    /**
     * 创建着色器
     * */
    const program = initShader(gl, VERTEX_SHADER_SOURCE, FRAGMENT_SHADER_SOURCE);

    const aPosition = gl.getAttribLocation(program, 'aPosition');

    const points = [];
    // ctx.onclick = function(event) {
    ctx.onmousemove = function(event) {
      // 坐标
      const x = event.clientX;
      const y = event.clientY;

      const domPosition = event.target.getBoundingClientRect();

      const domx = x - domPosition.left;                // 获取鼠标在画布的水平方向的相对位置
      const domy = y - domPosition.top;                 // 获取鼠标在画布的垂直方向的相对位置

      const halfWidth = ctx.offsetWidth / 2;            // 画布一半的宽度
      const halfHeight = ctx.offsetHeight / 2;          // 画布一半的高度

      const clickX = (domx - halfWidth) / halfWidth;    // 转换成webgl水平方向的-1和1
      const clickY = (halfHeight - domy) / halfHeight;  // 转换成webgl垂直方向的1和-1

      // gl.vertexAttrib2f(aPosition, clickX, clickY);
      // gl.drawArrays(gl.POINTS, 0, 1);

      points.push({
        clickX, clickY
      });

      for(let i=0; i < points.length; i++) {
        gl.vertexAttrib2f(aPosition, points[i].clickX, points[i].clickY);
        gl.drawArrays(gl.POINTS, 0, 1);
      }
    }
  </script>
</body>
</html>